package com.briup.security.config;

import com.briup.security.filter.AuthenticationTokenFilter;
import com.briup.security.handler.FailHandler;
import com.briup.security.handler.SuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("myDetailService")
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Bean
    public SuccessHandler successHandler() {
        return new SuccessHandler();
    }

    @Bean
    public FailHandler failHandler() {
        return new FailHandler();
    }


    @Bean
    public AuthenticationTokenFilter authenticationTokenFilter() {
        return new AuthenticationTokenFilter();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); // 添加过滤器到 UsernamePasswordAuthenticationFilter前面

        http.formLogin()
            .loginPage("/account/page") // 当请求需要认证,跳转到该地址
            .loginProcessingUrl("/account/login") // 请求认证地址
            .successHandler(successHandler())
            .failureHandler(failHandler())
           // .successForwardUrl("/account/success")
           // .failureForwardUrl("/account/fail")
            .and()
            .authorizeRequests()
            .antMatchers("/account/login","/account/page").permitAll() // 登录请求也不需要认证
            .antMatchers(
                        "/webjars/**",
                        "/api/**",
                        "/swagger-ui.html",
                        "/swagger-resources/**",
                        "/v2/**",
                        "/swagger-resources/**").permitAll() // swagger 界面不需要认证
            .anyRequest().authenticated()
            .and().csrf().disable();

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * 设置认证逻辑为用户自定义认证逻辑
         * 设置密码加密处理器为 BCryptPasswordEncoder
         */
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }
}
